package com.iisigroup.http.test;


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.iisigroup.http.test.RlAccount.Account;
/**
 * Hello world!
 * 參考https://hc.apache.org/httpcomponents-client-4.3.x/quickstart.html
 * 而做出來的測試程式碼
 */
public class App1 {

	public static void main(String[] args) throws Exception {
//		while (true) {
//			new App1().testMethod();
//		}
		new App1().multiProcess();
	}
	private List<String> getAllPage(final String prefix){
	    return new Page().getAllPages(prefix);
	}
	public void testMethod() throws ClientProtocolException, IOException{
//	    	final String prefix =  "http://192.168.10.18:6280";
//	    	final String prefix2 = "http://192.168.10.18:6280/rl/faces/";
//		final String prefix =  "http://140.92.86.173:6280";
//    	final String prefix2 = "http://140.92.86.173:6280/rl/faces/";
    	final String prefix =  "http://140.92.86.173:6180";
    	final String prefix2 = "http://140.92.86.173:6180/rl/faces/";
	    	final List<String> allPages = getAllPage(prefix2);
	    	
	    	final CloseableHttpClient httpclient = HttpClients.createDefault();
	    	final HttpGet httpGet = new HttpGet(prefix+"/rl/pages/common/login.jsp");
		//http://targethost/homepage
		//http://192.168.10.18:6280/rl/pages/common/login.jsp
	    	final CloseableHttpResponse response1 = httpclient.execute(httpGet);
		// The underlying HTTP connection is still held by the response object
		// to allow the response content to be streamed directly from the network socket.
		// In order to ensure correct deallocation of system resources
		// the user MUST call CloseableHttpResponse#close() from a finally clause.
		// Please note that if response content is not fully consumed the underlying
		// connection cannot be safely re-used and will be shut down and discarded
		// by the connection manager. 
		try {
//		    System.out.println(response1.getStatusLine());
		    HttpEntity entity1 = response1.getEntity();
		    // do something useful with the response body
		    // and ensure it is fully consumed
		    String content =EntityUtils.toString(entity1);
		    EntityUtils.consume(entity1);
		} finally {
		    response1.close();
		}
		///pages/j_spring_security_check
		//http://192.168.10.18:6280/rl/pages/j_spring_security_check
		HttpPost httpPost = new HttpPost(prefix+"/rl/faces/pages/j_spring_security_check");
		List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		Account account = 	RlAccount.getRandomAccount();
//		nvps.add(new BasicNameValuePair("j_username", account.getUser()));
//		nvps.add(new BasicNameValuePair("j_password", account.getPasswd()));
		nvps.add(new BasicNameValuePair("j_username", "RE0520123"));
		nvps.add(new BasicNameValuePair("j_password", "RE0520123"));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps));
		CloseableHttpResponse response2 = httpclient.execute(httpPost);

		try {
//		    System.out.println(response2.getStatusLine());
		    HttpEntity entity2 = response2.getEntity();
		    String content =EntityUtils.toString(entity2);
		    // do something useful with the response body
		    // and ensure it is fully consumed
		    EntityUtils.consume(entity2);
		} finally {
		    response2.close();
		}
		 
		
		//http://targethost/homepage
		//http://192.168.10.18:6280/rl/pages/common/login.jsp
		CloseableHttpResponse response03 = null;
		// The underlying HTTP connection is still held by the response object
		// to allow the response content to be streamed directly from the network socket.
		// In order to ensure correct deallocation of system resources
		// the user MUST call CloseableHttpResponse#close() from a finally clause.
		// Please note that if response content is not fully consumed the underlying
		// connection cannot be safely re-used and will be shut down and discarded
		// by the connection manager. 
		for (int c = 0; c < 60; c++) {
		    HttpGet httpGet03 = new HttpGet(prefix+"/rl/faces/pages/func/rl03100/rl03100.xhtml");
			
//		    final HttpGet httpGet03 = new HttpGet(allPages.get(RandomUtils.nextInt(allPages.size())));		    
//			InputStream ins = null;
			try {
				response03 = httpclient.execute(httpGet03);
//				System.out.println(response03.getStatusLine());
				HttpEntity entity3 = response03.getEntity();

				InputStream ins = entity3.getContent();
//				final List<String> lines = IOUtils.readLines(ins);
//				for (String line : lines) {
//					System.out.println(line);
//				}
				String content =EntityUtils.toString(entity3);
				// do something useful with the response body
				// and ensure it is fully consumed
				EntityUtils.consume(entity3);
				
			} finally {
				if (response03 != null) {
					response03.close();
				}
			}
		}
		//如果要測試戶籍員的反應...則要把httpclient.close();註解掉,這樣才會使得stuck thread 不會消失
//		httpclient.close();
	}
	public void multiProcess(){
		List<Future<List<String>>> data =null;
		final List<HttpTask> tasks = new ArrayList<HttpTask>();
		for(int j=0 ;j<10000;++j){
			tasks.add(new HttpTask());
		}
//		ExecutorService service = Executors.newCachedThreadPool();
				ExecutorService service = Executors.newFixedThreadPool(300);
        
        try {
        	 data = service.invokeAll(tasks, 10000, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
            service.shutdown();
        }
        if(data != null && data.size() > 0){
        	for(Future<List<String>> futureUnit :data ){
        		try {
					futureUnit.get();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
        	}
        }
	}
	public class HttpTask implements Callable<List<String>> {

		@Override
		public List<String> call() throws Exception {
			testMethod();
			return null;
		}}
}
